<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>VM绑定</title>
</head>
<body>
    <div id="root"></div>
    <template name="Count">
        <div>{{count}}</div>
        <div onclick="handleAddClick()">+</div>
    </template> 
</body>
<script>
    const tpl = document.querySelector('template');
    const root = document.querySelector('#root');

    // 正则表达式定义
    const telReg =/\{\{.+?\}\}/g; //匹配 {{xx}} 整个内容
    const contentReg = /(?<=(\{\{)).+?(?=(\}\}))/g // 匹配{{}}里面的xx


    const data = {
        count: 0
    }

    // 定义模板转换函数
    const parse = () => {
        return tpl.innerHTML.replace(telReg, (item)=>{
            const key = item.match(contentReg)[0];
            return data[key];
        })
    }
    // render，就是整个template转换成dom的流程
    const render = () => {
        root.innerHTML = parse();
    }
    render();

    // 劫持数据，当数据变更时，触发render函数
    var proxyCount = data.count;
    Object.defineProperty(data, 'count', {
        get(){
            return proxyCount;
        },
        set(newValue) { 
            console.log(newValue)
            proxyCount = newValue; 
            render();
        },
    })  

    // 定义点击事件
    const handleAddClick = () => {
        data.count = data.count + 1;
    }

  
</script>
</html>